package org.xiaoyu.rpc.proxy.support;

import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.AbstractInvoker;
import org.xiaoyu.rpc.Invoker;
import org.xiaoyu.rpc.common.url.URL;
import org.xiaoyu.rpc.proxy.ProxyFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created By Have
 * 2021/7/12 16:46
 */
public class JDKRpcProxyFactory implements ProxyFactory {

    @Override
    public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
    }

    @Override
    public <T> Invoker<T> getInvoker(Object proxy, Class<T> type, URL url) {
        return new AbstractInvoker<T>(proxy, type, url) {
            @Override
            public Object doInvoke(Object proxy, String methodName, Class<?>[] parameterTypes, Object[] parameters) {
                try {
                    Method method = proxy.getClass().getMethod(methodName, parameterTypes);
                    Object value = method.invoke(proxy, parameters);
                    return value;
                } catch (NoSuchMethodException | InvocationTargetException |IllegalAccessException e) {
                    return e;
                }
            }
        };
    }
}
